
from subprocess import check_output
import json, requests, re, fire


def dumptrace(t):
    i = t.find('{')
    j = json.loads(t[i:])
    ver = j['buildver']
    j['map'] = f'http://py.fr/jssrc/{ver}/index.js.map'
    print(j['map'])

    url = 'http://py.fr:8234/stack'
    #url = 'http://localhost:8001/stack'
    r = requests.post(url, json=j)
    if r.status_code != 200:
        open('/root/cdn/e.html', 'w').write(r.text)
        print('error', r.status_code)
        return
    assert r.status_code == 200, f'{r.text}'
    print(r.text)
    for e in json.loads(r.text):
        print(e)

class App:

    @staticmethod
    def tail():
        t = check_output('ssh fr tail tracelog/trace.log -n 1', shell=True, text=True)
        t = re.sub(r'file:.*?web-mobile', 'web-mobile', t)

    @staticmethod
    def db(id):
        import psycopg2
        conn_string = f"dbname=aimage user=postgres password=87^KgtCKscBW host=mon port=25432"
        conn = psycopg2.connect(conn_string)
        cur = conn.cursor()
        cur.execute('select raw from bugs_stack where id=%s', [id])
        d = cur.fetchone()[0]
        print(d)
        dumptrace(d)

    @staticmethod
    def mdb(id):
        for i in range(1000):
            App.db(id)


if __name__ == '__main__':
    fire.Fire(App)